<template>
  <div class="app-container pcmmeasurefeaturesManage">
    <el-card shadow="never" class="table-container">
      <div class="flex flex-row">
        <div class="flex-1">
          <el-form
            :model="searchParam"
            label-width="104px"
            label-position="right"
            size="large"
          >
            <SearchFormGroup
              :data="searchParam"
              :requiredList="['productId', 'gageEquipCode']"
              @change-search="handleSearchChange"
              @change-gageEquipCode="changeEquipCode"
            />
            <el-form-item label="特性名称" class="params">
              <el-select
                v-model="searchParam.paramIds"
                placeholder="请选择特性名称"
                clearable
                filterable
                :filter-method="customFilter5"
                multiple
                :disabled="!canSelectSpecific"
                class="select-device"
              >
                <el-option
                  v-for="item in filteredOptions5"
                  :key="item.id"
                  :label="item.paramName"
                  :value="item.id"
                />
              </el-select>
              <!-- <span v-if="canSelectSpecific" class="pl-[10px] c-[#666]"
                >共({{ specificList.length }})条</span
              > -->
            </el-form-item>
            <el-alert type="info" show-icon :closable="false">
              <p class="text-[15px] p-0">
                特性总计数量：
                <span
                  class="pl-[20px] text-[22px]"
                  style="font-family: DINPro"
                  >{{ specificList.length || 0 }}</span
                >
                <span class="pl-[50px]">已选：</span>
                <span
                  class="pl-[20px] text-[22px]"
                  style="font-family: DINPro"
                  >{{
                    searchParam.paramIds.length || specificList.length || 0
                  }}</span
                >
              </p>
            </el-alert>

            <el-form-item>
              <el-button @click="resetBtn" class="w-[100%] mt-[20px]">
                <i-ep-refresh />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="flex-1 flex flex-col">
          <div class="flex-1 flex flex-col mt-[50px] batchButton pl-[100px]">
            <el-button type="primary" :icon="Open" @click="batchOperation(1)">
              批量开启工单</el-button
            >
            <el-button type="primary" :icon="Remove" @click="batchOperation(2)"
              >批量关闭工单</el-button
            >
            <el-button
              type="primary"
              plain
              :icon="Open"
              @click="batchOperation(3)"
              class="mt-[20px]"
              >批量开启邮件</el-button
            >
            <el-button
              type="primary"
              :icon="Remove"
              plain
              @click="batchOperation(4)"
              >批量关闭邮件</el-button
            >
            <el-button
              type="warning"
              plain
              :icon="Open"
              @click="batchOperation(5)"
              class="mt-[20px]"
              >批量开启cpk</el-button
            >
            <el-button
              type="warning"
              :icon="Remove"
              plain
              @click="batchOperation(6)"
              >批量关闭cpk</el-button
            >
            <el-button
              type="success"
              :icon="Avatar"
              @click="batchOperationPerson()"
              class="mt-[20px]"
              >批量修改责任人</el-button
            >
          </div>
        </div>
      </div>
    </el-card>
    <el-dialog
      v-model="dialogFormVisible"
      title="批量修改责任人"
      width="450"
      align-center
    >
      <el-form :model="form">
        <el-form-item label="责任人" :label-width="formLabelWidth">
          <el-input
            v-model="form.responsibleUserName"
            placeholder="请选择人员"
            clearable
            readonly
            @click="openSelectOriganization"
          >
            <template #append>
              <el-button type="success" plain @click="openSelectOriganization"
                >选择</el-button
              >
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelChangeUser">取消</el-button>
          <el-button
            type="primary"
            @click="confirmChangeUser"
            :loading="userLoading"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 工单查看 弹窗组件 -->
    <SelectPersonDialog
      v-model:visible="personSelect.visible"
      :data="personSelect.data"
      @echo-info="getPersonSelect"
      :isMultiple="false"
      key="1"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useDictionary,
  useTable,
  useComputeTableHeight,
} from "@/utils/useTable";
import request from "@/utils/request";
import SearchFormGroup from "@/views/pcm/pcmMonitoring/components/SearchFormGroup1.vue";
import {
  getMdminspectiontoolApi,
  getMdmProcessEquipApi,
  getMdmProcessProjectApi,
  getMdmproductinfosApi,
  getMdmprojectinfosApi,
  getSpecificListApi,
  getMdmprocessListApi,
  getMdmProcessEquipApi1,
  getMdminspectionGroupApi,
} from "@/utils/commonData";
import pcmConfigMeasurementsEdit from "@/views/pcm/pcmconfigmeasurements/components/pcmconfigmeasurements-edit.vue";
import { Open, Remove, Avatar } from "@element-plus/icons-vue";
import { deepClone } from "@/utils/commonHooks";
import _ from "lodash-es";

defineOptions({
  name: "PCMPCMMEASUREFEATURESMANAGE",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/dmpDosPcm/pcmmeasurefeaturesgroup/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  // 工段
  workshopSectionId: "",
  workshopSectionCode: "",
  // 项目
  // projectCode: "",
  // projectId: "",
  // 工序
  processCode: "",
  processId: "",
  // 设备
  equipCode: "",
  equipId: "",
  // 产品型号
  productCode: "",
  productId: "",
  // 检具类型
  gageEquipToolKind: "",
  // 检具名称
  gageEquipCode: "",
  // 机器号
  gageEquipMarkCode: "",
  // 特性
  paramId: "",
  paramIds: [],
  toolGroupId: "",
};

const deleteParam = {
  api: "/dmpDosPcm/pcmmeasurefeaturesgroup/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const tableHeight = ref();

function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

// --------------------------------------------------------------------------------------------------------组件 开始
// 处理传回数据
const handleSearchChange = (data) => {
  Object.assign(searchParam.value, data);
  if (searchParam.value.gageEquipCode) {
    searchParam.value.toolGroupId = oldGageEquipList1.value.filter(
      (item) => item.groupCode == searchParam.value.gageEquipCode
    )[0].id;
  } else {
    searchParam.value.toolGroupId = "";
  }
};

// 间距变化
const changeEquipCode = (id: string) => {
  // if (id) {
  //   searchParam.paramId = "";
  // }
};
// --------------------------------------------------------------------------------------------------------组件 结束
const resetBtn = () => {
  searchParam.value = {
    ...searchParamInit,
  };
};

onMounted(() => {
  // 检具分组
  getGageEquipList1("");
});

const oldGageEquipList1 = ref<any>([]);
async function getGageEquipList1(type: string) {
  oldGageEquipList1.value = (await getMdminspectionGroupApi({})) || [];
}

// 获取特性值列表
const specificList = ref<any>([]);
const specificLoading = ref<any>(false);

async function getSpecificList() {
  specificLoading.value = true;
  specificList.value =
    (await getSpecificListApi({
      equipId: searchParam.value.equipId,
      toolGroupId: searchParam.value.toolGroupId,
      modelId: searchParam.value.productId,
      processId: searchParam.value.processId,
    }).finally(() => {
      specificLoading.value = false;
    })) || [];

  filteredOptions5.value = deepClone(specificList.value);
}
const filteredOptions5 = ref([]);
// 使用 debounce 包装过滤方法
const customFilter5 = _.debounce((query) => {
  if (!query) {
    filteredOptions5.value = [...specificList.value];
    return;
  }
  filteredOptions5.value = specificList.value.filter((option: any) =>
    option.paramName.toLowerCase().includes(query.toLowerCase())
  );
}, 300);

// 检测必填项，筛选特性值列表
const canSelectSpecific = ref(false);
watch(
  () => searchParam.value,
  (newVal) => {
    if (newVal.gageEquipCode && newVal.productCode) {
      canSelectSpecific.value = true;
      getSpecificList();
    } else {
      specificList.value = [];
      filteredOptions5.value = [];
      canSelectSpecific.value = false;
    }

    searchParam.value.gageEquipMarkCode = newVal.gageEquipCode;
  },
  {
    deep: true,
  }
);

watch(
  () => canSelectSpecific.value,
  (newVal) => {
    if (!newVal) {
      searchParam.value.paramIds = [];
    }
  }
);

function filterTxt(params: type) {
  if (params === 1) {
    return "请确认批量开启当前选中特性的工单？";
  }
  if (params === 2) {
    return "请确认批量关闭当前选中特性的工单？";
  }
  if (params === 3) {
    return "请确认批量开启当前选中特性的邮件？";
  }
  if (params === 4) {
    return "请确认批量关闭当前选中特性的邮件？";
  }
  if (params === 5) {
    return "请确认批量开启当前选中特性的cpk？";
  }
  if (params === 6) {
    return "请确认批量关闭当前选中特性的cpk？";
  }
}

const dialogFormVisible = ref(false);
const formLabelWidth = "70px";
const form = reactive({
  responsibleUserName: "",
  responsibleUserId: "",
});

const batchOperationPerson = async (type) => {
  if (!searchParam.value.productId) {
    ElMessage.error("请选择产品型号或型号描述");
    return;
  }
  if (!searchParam.value.toolGroupId) {
    ElMessage.error("请选择检具类别");
    return;
  }
  // if (!searchParam.value.paramIds.length) {
  //   ElMessage.error("请选择特性名称");
  //   return;
  // }
  dialogFormVisible.value = true;
};

function cancelChangeUser() {
  form.responsibleUserName = "";
  form.responsibleUserId = "";
  dialogFormVisible.value = false;
}

const userLoading = ref(false);
function confirmChangeUser() {
  if (!form.responsibleUserName) {
    ElMessage.error("请选择责任人");
    return;
  }

  let paramNames = [];
  if (searchParam.value.paramIds.length) {
    const idsToFind = new Set(searchParam.value.paramIds);
    const result = specificList.value.filter((item) => idsToFind.has(item.id));
    result.map((e) => {
      paramNames.push(e.paramName);
    });
  }

  const obj1 = searchParam.value;
  const obj = {
    workshopSectionId: obj1.workshopSectionId,
    workshopSectionCode: obj1.workshopSectionCode,
    processId: obj1.processId,
    processCode: obj1.processCode,
    equipId: obj1.equipId,
    equipCode: obj1.equipCode,
    modelId: obj1.productId,
    modelCode: obj1.productCode,
    modelName: obj1.productName,
    toolGroupId: obj1.toolGroupId,
    ids: obj1.paramIds,
    paramNames: paramNames ?? [],
  };

  userLoading.value = true;

  request({
    url: `/dmpDosPcm/pcmmeasurefeaturesgroup/batchSetting`,
    method: "post",
    data: {
      ...obj,
      responsibleUserName: form.responsibleUserName,
      responsibleUserId: form.responsibleUserId,
    },
  })
    .then((res) => {
      form.responsibleUserName = "";
      form.responsibleUserId = "";
      dialogFormVisible.value = false;
      ElMessage.success("操作成功");
    })
    .finally(() => {
      userLoading.value = false;
    });
}

const batchOperation = async (type) => {
  if (!searchParam.value.productId) {
    ElMessage.error("请选择产品型号或型号描述");
    return;
  }
  if (!searchParam.value.toolGroupId) {
    ElMessage.error("请选择检具类别");
    return;
  }
  // if (!searchParam.value.paramIds.length) {
  //   ElMessage.error("请选择特性名称");
  //   return;
  // }

  let paramNames = [];
  if (searchParam.value.paramIds.length) {
    const idsToFind = new Set(searchParam.value.paramIds);
    const result = specificList.value.filter((item) => idsToFind.has(item.id));
    result.map((e) => {
      paramNames.push(e.paramName);
    });
  }

  const obj1 = searchParam.value;
  const obj = {
    workshopSectionId: obj1.workshopSectionId,
    workshopSectionCode: obj1.workshopSectionCode,
    processId: obj1.processId,
    processCode: obj1.processCode,
    equipId: obj1.equipId,
    equipCode: obj1.equipCode,
    modelId: obj1.productId,
    modelCode: obj1.productCode,
    modelName: obj1.productName,
    toolGroupId: obj1.toolGroupId,
    ids: obj1.paramIds,
    paramNames: paramNames ?? [],
  };
  if (type === 1) {
    obj.isOrder = "1";
  }
  if (type === 2) {
    obj.isOrder = "0";
  }
  if (type === 3) {
    obj.isEmail = "1";
  }
  if (type === 4) {
    obj.isEmail = "0";
  }
  if (type === 5) {
    obj.isCalculate = "1";
  }
  if (type === 6) {
    obj.isCalculate = "0";
  }
  console.log("search", obj);
  let messageTxt = filterTxt(type);
  ElMessageBox.confirm(messageTxt, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = "操作中...";
        request({
          url: `/dmpDosPcm/pcmmeasurefeaturesgroup/batchSetting`,
          method: "post",
          data: obj,
        })
          .then((res) => {
            ElMessage.success("操作成功");
          })
          .finally(() => {
            instance.confirmButtonLoading = false;
            done();
          });
      } else {
        done();
      }
    },
  });
};

// 定义 人员选择器弹窗参数
const personSelect = reactive({
  visible: false,
  data: [],
});

// 打开 人员选择器弹窗
function openSelectOriganization() {
  personSelect.visible = true;
  personSelect.data = form.responsibleUserId
    ? [
        {
          id: form.responsibleUserId,
          firstName: form.responsibleUserName,
        },
      ]
    : [];
}

// 接收 人员选择器回调参数
function getPersonSelect(options: any) {
  if (options.length) {
    form.responsibleUserId = options[0].id;
    form.responsibleUserName = options[0].firstName;
  } else {
    form.responsibleUserId = "";
    form.responsibleUserName = "";
  }
}
</script>
<style lang="scss" scoped>
:deep(.select-device) {
  .el-tag {
    padding: 0 4px;
  }
}
.pcmmeasurefeaturesManage {
  :deep(.el-form) {
    .el-form-item__label {
      height: 36px;
      line-height: 36px;
    }
    .el-select {
      height: 36px;
      line-height: 36px;
      width: 100%;
    }
    .el-select .el-input {
      height: 36px;
      line-height: 36px;
    }
    .params {
      .el-select {
        height: auto !important;
        line-height: auto !important;
        width: 100%;
      }
      .el-select .el-input {
        height: auto !important;
        line-height: auto !important;
      }
    }
  }
  :deep(.el-card__body) {
    padding: 50px 30px;
    height: calc(100vh - 122px);
    overflow-y: auto;
  }
  .el-alert {
    padding: 0px;
  }
  .el-alert--info {
    padding-left: 40px;
  }
  .batchButton {
    :deep(.el-button) {
      margin-left: 0px;
      margin-bottom: 10px;
      width: 160px;
      height: 38px;
      display: inline-block;
      // background: #1887f7;
      // background: #4a6cf7;
      // color: white;
      // padding: 16px 40px;
      border-radius: 8px;
      text-decoration: none;
      font-weight: 600;
      font-size: 15px;
      transition: all 0.3s;
      // box-shadow: 0 4px 10px rgba(74, 108, 247, 0.2);
      position: relative;
      overflow: hidden;
      padding: 0px;
      display: flex;
      .el-icon {
        font-size: 22px !important;
        width: 22px;
        height: 22px;
        svg {
          font-size: 22px !important;
          width: 22px;
          height: 22px;
        }
      }
    }
  }
}
</style>
